import { BASE_URL } from "../../utils/config";

interface Course {
  id: number;
  courseName: string;
  icon: string;
  color: string;
  checkType: number;
}

Page({
  data: {
    isClockIn: false,
    course: {} as Course,
    ctx: null as any,
    points: [] as {x: number; y: number}[],
    numbers: [] as number[],
    isDrawing: false,
    gridSize: 3, // 九宫格大小
    cellSize: 0, // 单元格大小
    padding: 50, // 九宫格内边距
    gridPoints: [] as {x: number; y: number; number: number}[] // 九宫格点位置
  },

  onLoad(options: any) {
    // 获取课程数据
    this.fetchCourse(options.courseId);
    // 初始化画布
    this.initCanvas();
  },

  async initCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#gestureCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');

        // 设置画布大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);

        // 设置画笔样式
        ctx.lineWidth = 4;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        ctx.strokeStyle = '#3b82f6';

        this.setData({ ctx }, () => {
          // 绘制九宫格
          this.drawGrid();
        });
      });
  },

  findNearestPoint(x: number, y: number) {
    const { gridPoints, cellSize } = this.data;
    const threshold = cellSize / 3; // 设置判定阈值

    for (const point of gridPoints) {
      const distance = Math.sqrt(
        Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2)
      );
      if (distance < threshold) {
        return point;
      }
    }
    return null;
  },

  onTouchStart(e: WechatMiniprogram.TouchEvent) {
    const { x, y } = e.touches[0];
    const nearestPoint = this.findNearestPoint(x, y);

    if (nearestPoint) {
      this.setData({
        isDrawing: true,
        points: [{ x: nearestPoint.x, y: nearestPoint.y }],
        numbers: [nearestPoint.number]
      });

      this.data.ctx.beginPath();
      this.data.ctx.moveTo(nearestPoint.x, nearestPoint.y);
    }
  },

  onTouchMove(e: WechatMiniprogram.TouchEvent) {
    if (!this.data.isDrawing) return;

    const { x, y } = e.touches[0];
    const nearestPoint = this.findNearestPoint(x, y);

    if (nearestPoint) {
      const lastPoint = this.data.points[this.data.points.length - 1];
      if (lastPoint.x !== nearestPoint.x || lastPoint.y !== nearestPoint.y) {
        const points = [...this.data.points, { x: nearestPoint.x, y: nearestPoint.y }];
        const numbers = [...this.data.numbers, nearestPoint.number];
        this.setData({ points, numbers });

        this.data.ctx.lineTo(nearestPoint.x, nearestPoint.y);
        this.data.ctx.stroke();
      }
    }
  },

  onTouchEnd() {
    this.setData({ isDrawing: false });
    // 重新绘制九宫格，保持数字可见
    this.drawGrid();
  },

  clearCanvas() {
    const { ctx } = this.data;
    const canvas = ctx.canvas;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    this.setData({ points: [] });
    this.drawGrid();
  },

  drawGrid() {
    const { ctx } = this.data;
    const canvas = ctx.canvas;
    const width = canvas.width / wx.getSystemInfoSync().pixelRatio;
    const height = canvas.height / wx.getSystemInfoSync().pixelRatio;
    const { gridSize, padding, points } = this.data;

    // 计算单元格大小
    const cellSize = Math.min(
      (width - padding * 2) / gridSize,
      (height - padding * 2) / gridSize
    );

    // 计算起始位置，使九宫格居中
    const startX = (width - cellSize * gridSize) / 2;
    const startY = (height - cellSize * gridSize) / 2;

    // 存储九宫格点位置
    const gridPoints = [];

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制连接线
    if (points.length > 1) {
      ctx.beginPath();
      ctx.strokeStyle = '#3b82f6';
      ctx.lineWidth = 4;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.moveTo(points[0].x, points[0].y);
      for (let i = 1; i < points.length; i++) {
        ctx.lineTo(points[i].x, points[i].y);
      }
      ctx.stroke();
    }

    // 绘制九宫格点位
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = `${cellSize / 3}px Arial`;

    for (let i = 0; i < gridSize; i++) {
      for (let j = 0; j < gridSize; j++) {
        const x = startX + j * cellSize;
        const y = startY + i * cellSize;
        const centerX = x + cellSize / 2;
        const centerY = y + cellSize / 2;
        const number = i * gridSize + j + 1;
        const radius = cellSize / 4;

        // 检查点是否被选中
        const isSelected = points.some(point => 
          point.x === centerX && point.y === centerY
        );

        // 绘制圆形
        ctx.beginPath();
        ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
        ctx.fillStyle = isSelected ? '#2563eb' : '#f3f4f6';
        ctx.fill();

        // 绘制数字
        ctx.fillStyle = isSelected ? '#ffffff' : '#6b7280';
        ctx.font = `bold ${cellSize / 3}px Arial`;
        ctx.fillText(number.toString(), centerX, centerY);

        // 存储点位置信息
        gridPoints.push({
          x: centerX,
          y: centerY,
          number
        });
      }
    }
    ctx.restore();

    this.setData({
      cellSize,
      gridPoints
    });
  },

  fetchCourse(courseId: number) {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/course/selectOne`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        id: courseId
      },
      success: (res: any) => {
        const { code, data } = res.data;
        if (code === 200) {
          this.setData({
            course: data
          });
        } else {
          wx.showToast({
            title: res.data.msg || '查询失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '查询失败',
          icon: 'error'
        });
      }
    });
  },

  gestureCheck() {
    console.log(this.data.numbers);

    // 将points数组转换为字符串
    const gestureStr = this.data.numbers.join('');
    
    // 与课程设置的手势密码比较
    if (gestureStr !== this.data.course.checkContent) {
      wx.showToast({
        title: '手势密码错误',
        icon: 'error'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/check/gestureSave`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        courseId: this.data.course.id,
        points: this.data.points
      },
      success: (res: any) => {
        const { code } = res.data;
        if (code === 200) {
          this.setData({
            isClockIn: true
          }, () => {
            wx.showToast({
              title: '打卡成功',
              icon: 'success'
            });

            setTimeout(() => {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }, 1000);
          });
        } else {
          wx.showToast({
            title: res.data.msg || '打卡失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '打卡失败',
          icon: 'error'
        });
      }
    });
  }
});